package com.example.cores_torage;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class RreferenceStorage extends AppCompatActivity implements View.OnClickListener {
    TextView etName;
    TextView etAge;
    TextView etHeight;
    TextView etWeight;
    CheckBox cbmarried;
    SharedPreferences preference;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_rreference_storage);

        etName = findViewById(R.id.et_name);
        etAge = findViewById(R.id.et_age);
        etHeight = findViewById(R.id.et_height);
        etWeight = findViewById(R.id.et_weight);
        cbmarried = findViewById(R.id.cb_marriage);
        Button btnConfirm = findViewById(R.id.btn_confirm);

        preference = getSharedPreferences("confi", Context.MODE_PRIVATE);
        reload();

        btnConfirm.setOnClickListener(this);
    }

    private void reload() {
        String name = preference.getString("name", null);
        if (name != null) {
            etName.setText(name);
        }

        int age = preference.getInt("age", 0);
        if (age != 0) {
            etAge.setText(String.valueOf(age));
        }

        float height = preference.getFloat("height", 0f);
        if (height != 0f) {
            etHeight.setText(String.valueOf(height));
        }

        int weight = preference.getInt("weight", 0);
        if (weight != 0) {
            etWeight.setText(String.valueOf(weight));
        }

        boolean married = preference.getBoolean("married", false);
        cbmarried.setChecked(married);

    }


    @Override
    public void onClick(View view) {
        String name = etName.getText().toString();
        String age = etAge.getText().toString();
        String height = etHeight.getText().toString();
        String weight = etWeight.getText().toString();
        boolean married = cbmarried.isChecked();

        SharedPreferences.Editor edit = preference.edit();
        edit.putString("name", name);
        edit.putInt("age", Integer.parseInt(age));
        edit.putFloat("height", Float.parseFloat(height));
        edit.putInt("weight", Integer.parseInt(weight));
        edit.putBoolean("married", married);
        edit.commit();
        Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
    }
}